﻿using Microsoft.EntityFrameworkCore;
using System.Text.RegularExpressions;
using tju.cme.BookStore2024.webapi.Models.EF;
using tju.cme.BookStore2024.webapi.Models.ViewModels.Chapter;
using tju.cme.BookStore2024.webapi.Models.Tools;

namespace tju.cme.BookStore2024.webapi.Services
{
    /// <summary>
    /// 与T032chapter表相关的服务
    /// </summary>
    public class ChapterServices(BookStore2024Context context)
    {


        /// <summary>
        /// 新建章节
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task GreateChapterAsync(ChapterCreateModel model, Guid authorId)
        {

            var novel = await context.V011auWith031NoWith032ChWith022Admins.FirstOrDefaultAsync(m => m.AuthorId == authorId && m.NovelId == model.NovelId);
            if (novel == null) throw new Exception("未找到该小说");

            var maxChapterNumber = await context.T032chapters
                    .Where(c => c.NovelId == model.NovelId)
                    .MaxAsync(c => (int?)c.ChapterNumber) ?? 0;
            // 创建新的章节记录
            var newChapter = new T032chapter()
            {
                Id = Guid.NewGuid(), // 生成新的章节Id
                ChapterNumber = maxChapterNumber + 1, // 章节编号
                ChapterTitle = model.ChapterTitle, // 章节标题
                ChapterText = model.ChapterText, // 章节文本
                ChapterGenerateTime = DateTime.Now,
                LastModifyTime = DateTime.Now,
                ChapterPublishTime = DateTime.Now,
                //ChapterTotalWords = (Regex.Replace(model.ChapterText, @"\s+", "")).Length,
                NovelId = model.NovelId, //所属小说Id
                Status = "Draft"

            };

            await context.T032chapters.AddAsync(newChapter);
            await context.SaveChangesAsync();

        }


        /// <summary>
        /// 修改章节
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task EditChapterAsync(ChapterModifyModel model, Guid authorId)
        {
            if (! await IsAuthorOfChapterAsync(authorId, model.Id)) throw new Exception("违规操作");
            var chapter = await context.T032chapters.FirstOrDefaultAsync(m => m.Id == model.Id);
            if (chapter == null) throw new Exception("无效id");
            if (model.Status != "Draft" && model.Status != "Submitted") throw new Exception("章节状态设置违规");
            chapter.ChapterTitle = model.ChapterTitle;
            chapter.ChapterText = model.ChapterText;
            //chapter.ChapterTotalWords = (Regex.Replace(model.ChapterText, @"\s+", "")).Length;
            chapter.LastModifyTime = DateTime.Now;
            chapter.Status = model.Status;  //"草稿"或"提交"
            await context.SaveChangesAsync();
            //else
            //{
            //    if (model.Status != "Draft" && model.Status != "Submitted") throw new Exception("章节状态设置违规");

            //    //如果章节状态是“草稿”或“已拒绝”
            //    if (chapter.Status== "Draft" || chapter.Status == "Rejected")
            //    {
            //        chapter.ChapterTitle = model.ChapterTitle;
            //        chapter.ChapterText = model.ChapterText;
            //        chapter.ChapterTotalWords = (Regex.Replace(model.ChapterText, @"\s+", "")).Length;
            //        chapter.LastModifyTime = DateTime.Now;
            //        chapter.Status = model.Status;  //"草稿"或"提交"
            //        await context.SaveChangesAsync();
            //    }

            //    //如果章节状态是"已批准"或"已发布"
            //    if(chapter.Status == "Approved" || chapter.Status == "Published" || chapter.Status == "Submitted")
            //    {
            //        //创建一条新的章节记录
            //        var updateChapter = new T032chapter()
            //        {
            //            Id = Guid.NewGuid(), // 生成新的章节Id
            //            ChapterNumber = chapter.ChapterNumber, // 章节编号
            //            ChapterTitle = model.ChapterTitle, // 章节标题
            //            ChapterText = model.ChapterText, // 章节文本
            //            ChapterGenerateTime = DateTime.Now,
            //            LastModifyTime = DateTime.Now,
            //            //ChapterTotalWords = (Regex.Replace(model.ChapterText, @"\s+", "")).Length,
            //            NovelId = chapter.NovelId,
            //            Status = model.Status //"草稿"或"提交"
            //        };
            //        await context.T032chapters.AddAsync(updateChapter);
            //        await context.SaveChangesAsync();
            //    }

            //}

        }

        /// <summary>
        /// 根据小说Id获取所有章节
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IEnumerable<T032chapter>> GetAllByNovelIdAsync(Guid id)
        {
            return await context.T032chapters.Where(m => m.NovelId == id).OrderBy(m => m.ChapterNumber).ToListAsync();
        }



        /// <summary>
        /// 根据小说Id获取所有已上传章节
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IEnumerable<T032chapter>> GetUploadedByNovelIdAsync(Guid id)
        {
            return await context.T032chapters.Where(m => m.NovelId == id && m.Status == "Published").ToListAsync();
        }


        /// <summary>
        /// 将章节提交给管理员
        /// </summary>
        /// <param name="chapterId"></param>
        /// <returns></returns>
        public async Task UpToAdminAsync(Guid chapterId, Guid authorId)
        {
            if (!await IsAuthorOfChapterAsync(authorId, chapterId)) throw new Exception("违规操作");
            
            var chapter = await context.T032chapters.FirstOrDefaultAsync(m =>m. Id == chapterId);

            if (chapter == null) throw new Exception("无效章节");

            //章节不为空且状态为“草稿”
            else if ( chapter.Status == "Draft")
            {
                //更改章节状态为“已提交”
                chapter.Status = "Submitted";
                // 保存更改到数据库
                await context.SaveChangesAsync();

            }
            else throw new Exception("无法提交");
        }


        /// <summary>
        /// 管理员审核已提交章节
        /// </summary>
        /// <param name="chapterId"></param>
        /// <param name="isApprove"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task ExamineChapterAsync(ChapterExamineModel model , Guid adminId)
        {
            if (!await IsAdminOfChapterAsync(adminId, model.Id)) throw new Exception("违规操作");

            var chapter = await context.T032chapters.FirstOrDefaultAsync(m => m.Id == model.Id);
            if (chapter == null) throw new Exception("未找到该章节");
            if (chapter.Status != "Submitted") throw new Exception("章节未提交或已审核");
            if (model.Status != "Approved" && model.Status != "Rejected") throw new Exception("审核状态设置违规");

            chapter.Status = model.Status;
            await context.SaveChangesAsync();

        }





        /// <summary>
        /// 管理员将审核通过的章节上传到该小说
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isUpload"></param>
        /// <returns></returns>
        public async Task UploadAsync(Guid adminId , Guid chapterId)
        {

            if (!await IsAdminOfChapterAsync(adminId, chapterId)) throw new Exception("违规操作");
            // 待上传的章节
            var chapter = await context.T032chapters.FirstOrDefaultAsync(m => m.Id == chapterId);

            //如果找到该章节
            if (chapter != null)
            {

                //如果该章节通过审核
                if (chapter.Status == "Approved")
                {
                    //当前章节总数
                    //int totalUpload = await context.T032chapters.CountAsync(m => m.NovelId == chapter.NovelId && m.Status == "Published");
                    var maxChapterNumber = await context.T032chapters
                    .Where(c => c.NovelId == chapter.NovelId && c.Status == "Published")
                    .MaxAsync(c => (int?)c.ChapterNumber) ?? 0;



                    //如果符合按章节顺序上传
                    if (chapter.ChapterNumber - maxChapterNumber <= 1)
                    {
                        //更改章节状态为“已发布”
                        chapter.Status = "Published";

                        //创建章节发布时间
                        chapter.ChapterPublishTime = DateTime.Now;
                        await context.SaveChangesAsync();


                    }
                    else throw new Exception("未按顺序上传");

                }
                else throw new Exception("该章节未通过审核");
            }
            else throw new Exception("未找到该章节");


        }


        /// <summary>
        /// 判断是否是章节的作者
        /// </summary>
        /// <param name="authorId"></param>
        /// <param name="chapterId"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<bool> IsAuthorOfChapterAsync(Guid authorId, Guid chapterId)
        {
            var vchapter = await context.V011auWith031NoWith032ChWith022Admins
                .FirstOrDefaultAsync(nca => nca.ChapterId == chapterId);

            if (vchapter == null) throw new Exception("该章节不存在");

            return vchapter.AuthorId == authorId;
        }


        /// <summary>
        /// 判断是否是章节的管理员
        /// </summary>
        /// <param name="adminId"></param>
        /// <param name="chapterId"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<bool> IsAdminOfChapterAsync(Guid adminId, Guid chapterId)
        {
            var vchapter = await context.V011auWith031NoWith032ChWith022Admins
                .FirstOrDefaultAsync(nca => nca.ChapterId == chapterId);

            if (vchapter == null) throw new Exception("该章节不存在");

            return vchapter.AdminId == adminId;
        }

    }
}
